package com.google.code.netbuilder.dal.providers.jpa;

import java.io.Serializable;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.google.code.netbuilder.dal.entities.Equipment;
import com.google.code.netbuilder.dal.providers.IEquipmentProvider;
/**
 * Class is JPA implementation of DAO for Equipment Entity
 * Uses EntityManager from PersistenceContext
 * @author Sergey Kozlov
 * 
 *
 */
@Stateless
public class EquipmentProviderJPA implements IEquipmentProvider, Serializable{

	private static final long serialVersionUID = -6078267042657526711L;
	
	@PersistenceContext(unitName = "NetBuilder")
    EntityManager em;
	
	public EquipmentProviderJPA(){
		
	}
	
	@Override
	public void save(Equipment entity) throws RuntimeException {
		em.persist(entity);
	}

	@Override
	public void update(Equipment entity) throws RuntimeException {
		em.merge(entity);
	}

	@Override
	public void delete(Equipment entity) throws RuntimeException {
		em.remove(entity);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Equipment> findAll() throws RuntimeException {
		List<Equipment> res;
		res = (List<Equipment>) em.createQuery("select e from Equipment e").getResultList();
		return res;
	}

	@Override
	public Equipment findByID(Integer id) throws RuntimeException {
		Query q = em.createQuery("select e from Equipment e where e.id = :id").setParameter("id", id);
		return (Equipment)q.getSingleResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Equipment> getEquipmentsByAddress(String address) {
		Query q = em.createQuery("select e from Equipment e where e.address = :address").setParameter("address", address);
		return (List<Equipment>)q.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Equipment> getEquipmentsByName(String name) {
		Query q = em.createQuery("select e from Equipment e where e.name = :name").setParameter("name", name);
		return (List<Equipment>)q.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Equipment> getEquipmentsByType(String type) {
		Query q = em.createQuery("select e from Equipment e where e.type = :type").setParameter("type", type);
		return (List<Equipment>)q.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Equipment> getEquipmentsByState(int objectState) {
		Query q = em.createQuery("select e from Equipment e where e.objectState = :objectState").setParameter("objectState", objectState);
		return (List<Equipment>)q.getResultList();
	}

	
}
